package com.epoch.fy.user.controller;

import java.io.File;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

import com.epoch.base.annotation.ControllerBind;
import com.epoch.base.controller.BaseController;
import com.epoch.base.interceptor.FrontAuthInterceptor;
import com.epoch.base.interceptor.UserAuthInterceptor;
import com.epoch.base.oss.OSSFactory;
import com.epoch.base.util.CommonUtil;
import com.epoch.base.util.DateUtils;
import com.epoch.fy.post.dao.Post;
import com.epoch.fy.post.dao.ReplayPost;
import com.epoch.fy.user.dao.LevelSet;
import com.epoch.fy.user.dao.User;
import com.epoch.fy.user.dao.UserSign;
import com.epoch.fy.user.service.UserService;
import com.jfinal.aop.Before;
import com.jfinal.kit.HashKit;
import com.jfinal.kit.Kv;
import com.jfinal.kit.Ret;
import com.jfinal.kit.StrKit;
import com.jfinal.plugin.activerecord.Db;
import com.jfinal.plugin.activerecord.SqlPara;
import com.jfinal.plugin.ehcache.CacheKit;
import com.jfinal.upload.UploadFile;
/**
 * 
* <p>Title: MyController.java</p>  
* <p>Description: </p>  
* @author 张清磊
* @QQ 544188838
* @date 2018年9月24日
 */
@ControllerBind(controllerKey = "/my")
public class MyController extends BaseController{
	
	
	@Before(FrontAuthInterceptor.class)
	public void my() {
		Integer userId = getUserId();
		UserSign userSign = UserService.me.getUserSign(userId);
		LevelSet level = new LevelSet();
		setAttr("signed", 0);
		setAttr("experience", 1);
		if(null != userSign) {
			Date date = userSign.getDate(UserSign.SIGN_TIME);
			int signCount = userSign.getInt(UserSign.SIGN_COUNT);
			int kiss = UserService.me.getGold(signCount);
			if(CommonUtil.isNow(date)) {
				setAttr("signed", 1);
			}
			setAttr("experience", kiss);
			//检测是否为VIP会员，如果是把会员标识返回回去
			level = LevelSet.dao.findById(userSign.getStr(UserSign.LEVEL));
		}
		setAttr("level", level);
		render("/community/my/my.html");
	}
	
	@Before(FrontAuthInterceptor.class)
	public void index() {
		setAttr("user", getUser(getUserId()));
		Kv param = Kv.create();
		param.set("user_id",getUserId());
		SqlPara sqlPara = Db.getSqlPara("fly.findPostTopById", param);
		List<Post>  postList = Post.dao.find(sqlPara);
		sqlPara = Db.getSqlPara("fly.findPostReplayTopById", param);
		List<ReplayPost>  replayPostList = ReplayPost.dao.find(sqlPara);
		setAttr("postList", postList);
		setAttr("replayPostList", replayPostList);
		render("/community/my/index.html");
	}
	
	@Before(FrontAuthInterceptor.class)
	public void mySet() {
		setAttr("user", getUser(getUserId()));
		render("/community/my/myset.html");
	}
	
	@Before(FrontAuthInterceptor.class)
	public void post() {
		render("/community/my/post.html");
	}
	
	@Before(FrontAuthInterceptor.class)
	public void product() {
		render("/community/my/product.html");
	}
	
	@Before(UserAuthInterceptor.class)
	public void signin() {
		Integer userId = getUserId();
		UserSign userSign = UserService.me.getUserSign(userId);
		String sessionId = getCookie(UserService.sessionIdName);
		if(null == userSign) {
			userSign = new UserSign();
			userSign.set(UserSign.USER_ID, userId);
			userSign.set(UserSign.SIGN_TIME, DateUtils.getCurrentDate());
			userSign.set(UserSign.SIGN_COUNT, 1);
			userSign.set(UserSign.SIGN_ALL_COUNT, 1);
			userSign.set(UserSign.GOLD, 0);
			userSign.set(UserSign.EXP, 0);
			userSign.set(UserSign.LEVEL, UserService.me.getLevelSetId(0).getInt(LevelSet.ID));
			userSign.set(UserSign.LEVEL_NAME, UserService.me.getLevelSetId(0).getStr(LevelSet.NAME));
			userSign.set(UserSign.LEVEL_IS_VIP, UserService.me.getLevelSetId(0).getStr(LevelSet.IS_VIP));
			userSign.save();
			CacheKit.removeAll(UserService.userSignCacheName);
			CacheKit.put(UserService.userSignCacheName, sessionId, userSign);
			renderSuccess("签到成功",Ret.by("experience", 1).set("signed", true).set("days", 1).set("kiss",1));
		}else{
			Date date = userSign.getDate(UserSign.SIGN_TIME);
			if(CommonUtil.isNow(date)) {
				renderFail("已经签到，不能再次签到",Ret.by("signed", false));
			}else {
				//先判断是否是连续签到，如果是连续签到，则连续签到次数增长1，否则置为1
				if(CommonUtil.getDifferenceDay(date) == 1) {
					userSign.set(UserSign.SIGN_COUNT, userSign.getInt(UserSign.SIGN_COUNT)+1);
				}else {
					userSign.set(UserSign.SIGN_COUNT, 1);
				}
				userSign.set(UserSign.SIGN_ALL_COUNT, userSign.getInt(UserSign.SIGN_ALL_COUNT)+1);
				userSign.set(UserSign.SIGN_TIME, DateUtils.getCurrentDate());
				int signCount = userSign.getInt(UserSign.SIGN_COUNT);
				int gold = UserService.me.getGold(signCount);
				userSign.set(UserSign.GOLD, userSign.getInt(UserSign.GOLD)+gold);
				userSign.set(UserSign.LEVEL, UserService.me.getLevelSetId(userSign.getInt(UserSign.EXP)).getInt(LevelSet.ID));
				userSign.set(UserSign.LEVEL_NAME, UserService.me.getLevelSetId(userSign.getInt(UserSign.EXP)).getStr(LevelSet.NAME));
				userSign.set(UserSign.LEVEL_IS_VIP, UserService.me.getLevelSetId(userSign.getInt(UserSign.EXP)).getStr(LevelSet.IS_VIP));
				userSign.update();
				CacheKit.removeAll(UserService.userSignCacheName);
				CacheKit.put(UserService.userSignCacheName, sessionId, userSign);
				renderSuccess("签到成功",Ret.by("experience", gold).set("signed", true).set("days", userSign.getInt(UserSign.SIGN_COUNT)).set("kiss",userSign.getInt(UserSign.GOLD)));
			}
		}
		
	}
	
	public void signRank() {
		Kv param = Kv.create();
		param.set("user_id",getUserId());
		SqlPara sqlPara = Db.getSqlPara("fly.findLatestSignData", param);
		List<Post>  signData = Post.dao.find(sqlPara);
		sqlPara = Db.getSqlPara("fly.findLatestAllSignData", param);
		List<Post>  allSignData = Post.dao.find(sqlPara);
		List<Object> list = new ArrayList<Object>();
		list.add(signData);
		list.add(signData);
		list.add(allSignData);
		renderSuccess("",Ret.by("data", list));
	}
	
	public void u() {
		String id = getAttr("view");
		setAttr("user", getUser(Integer.parseInt(id)));
		Kv param = Kv.create();
		param.set("user_id",id);
		SqlPara sqlPara = Db.getSqlPara("fly.findPostTopById", param);
		List<Post>  postList = Post.dao.find(sqlPara);
		sqlPara = Db.getSqlPara("fly.findPostReplayTopById", param);
		List<ReplayPost>  replayPostList = ReplayPost.dao.find(sqlPara);
		setAttr("postList", postList);
		setAttr("replayPostList", replayPostList);
		render("/community/my/index.html");
	}
	
	@Before(FrontAuthInterceptor.class)
	public void uploadHead() {
		String contentType = getRequest().getContentType();
        boolean flag = contentType != null && contentType.toLowerCase().indexOf("multipart") != -1;
        if(!flag) {
        	renderJson(Ret.fail().set("message", "不是MultipartRequest，不能上传文件"));
            return;
        }
        
        UploadFile uploadFile = getFile();
        if (uploadFile == null) {
            renderJson(Ret.fail().set("message", "没有接收到任何文件上传"));
            return;
        }
        File file = uploadFile.getFile();
        long size_check = 50 * 1024;
        long usr_upLoad_file_size = file.length();
        if (usr_upLoad_file_size < size_check) {
        	String path = OSSFactory.build().upload(file);
        	Integer id = getUserId();
        	User user  = User.dao.findById(id);
        	user.set(User.AVATAR, path);
        	user.update();
        	file.delete();
            renderJson(Ret.ok().set("url", path).set("message", "上传成功"));
        } else {
            file.delete();
            renderFail("头像图片请限制在50K以内!");
        }
	}
	
	@Before(FrontAuthInterceptor.class)
	public void set() {
		String pass = getPara("pass");
		String repass = getPara("repass");
		if(pass.length()<6 || pass.length()>16) {
			renderFail("密码必须为6到16个字符");
		}else if(repass.length()<6 || repass.length()>16) {
			renderFail("密码必须为6到16个字符");
		}else if(!pass.equals(repass)) {
			renderFail("密码不一致，请重新填写");
		}else {
			User user = getUser(getUserId());
			String salt = StrKit.getRandomUUID();
			String hashedPass = HashKit.sha256(salt + pass);
			user.set(User.SALT, salt);
			user.set(User.PASSWORD, hashedPass);
			user.update();
			renderSuccess("修改成功！",Ret.by("button", "ok"));
		}
	}
	
	@Before(FrontAuthInterceptor.class)
	public void message() {
		render("/community/my/message.html");
	}

}
